package at.fhooe.mcm.logic.sensors.entities;

import java.io.Serializable;

import at.fhooe.mcm.logic.core.Core;
import at.fhooe.mcm.logic.event.EventManager;
import at.fhooe.mcm.logic.logging.ConsoleLoggingService;
import at.fhooe.mcm.logic.sensors.Sensor;
import at.fhooe.mcm.logic.sensors.events.SensorUpdatedEvent;

public class HumiditySensor extends Sensor implements Serializable
{
	/**
	 * 
	 */
	private static final long	serialVersionUID	= -7320721772352544778L;

	private double				m_currentHumidity;
	private boolean				m_isPushingData;

	public HumiditySensor(Core _core, String _id, String _name, boolean _isPublic, boolean _isPull, int _updatePeriod)
	{
		super(_core, _id, _name, _isPublic, _isPull, _updatePeriod);
	}

	public static final String	TYPE	= "HumiditySensor";

	@Override
	public String getType()
	{
		return TYPE;
	}

	@Override
	protected void setUp()
	{
		if (!m_isPull)
		{
			m_isPushingData = true;
			m_thread.start();
		}
	}

	@Override
	protected void tearDown()
	{
		if (!m_isPull)
		{
			m_isPushingData = false;
		}
	}

	@Override
	public void update()
	{
		if (m_isPull)
		{
			m_currentHumidity = Math.random() * 100;
			SensorUpdatedEvent event = new SensorUpdatedEvent(m_id, TYPE, m_name, m_currentHumidity);
			EventManager.getInstance(m_core).enqueueEvent(event);

			ConsoleLoggingService.getInstance(m_core).logInfo("AIRPRESSURE SENSOR", "Pull " + String.valueOf(m_currentHumidity));

		}
	}

	@Override
	public void run()
	{
		try
		{
			while (m_isPushingData)
			{
				m_currentHumidity = Math.random() * 100;
				if (!m_isPull)
				{
					SensorUpdatedEvent event = new SensorUpdatedEvent(m_id, TYPE, m_name, m_currentHumidity);
					EventManager.getInstance(m_core).enqueueEvent(event);

					ConsoleLoggingService.getInstance(m_core).logInfo("HUMIDITY SENSOR", "Push " + String.valueOf(m_currentHumidity));

				}

				Thread.sleep(m_updatePeriod);
			}
		}
		catch (InterruptedException e)
		{
			ConsoleLoggingService.getInstance(m_core).logDebug("HUMIDITY SENSOR", e.getMessage());
		}
	}
}
